package com.yusheng.tr.multi.utils;

import com.aspose.words.*;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @author : LCheng
 * @date : 2020-12-25 13:47
 * description : Aspose工具类
 */
public class AsposeUtil {


    /**
     * word转pdf
     *
     * @param wordPath word文件保存的路径
     * @param pdfPath  转换后pdf文件保存的路径
     * @author LCheng
     * @date 2020/12/25 13:51
     */
    @SneakyThrows
    public static void wordToPdf(String wordPath, String pdfPath) {
        File file = new File(pdfPath);
        try (FileOutputStream os = new FileOutputStream(file)) {
            Document doc = new Document(wordPath);
            removeWatermarks(doc);
            doc.save(os, SaveFormat.PDF);
        }
    }

    private static void removeWatermarks(Document doc) throws Exception {
        // Iterate through all sections in the document
        for (Section section : doc.getSections()) {
            // Iterate through all headers and footers in the section
            for (HeaderFooter headerFooter : section.getHeadersFooters()) {
                // Remove watermark shapes from headers/footers
                removeWatermarkShapes(headerFooter);
            }
        }

        // Remove watermark shapes from the main body of the document
        removeWatermarkShapes(doc);
    }

    private static void removeWatermarkShapes(CompositeNode<?> node) throws Exception {
        // Get all shapes in the node (section, header/footer, or main body)
        NodeCollection<Shape> shapes = node.getChildNodes(NodeType.SHAPE, true);

        // Iterate through shapes and remove watermarks based on your criteria
        for (Shape shape : shapes) {
            // You may need to adjust the condition based on the specific characteristics of the watermark
            if (shape.isWordArt()) {
                shape.remove();
            }
        }
    }

}

